<?php

namespace App\Http\Controllers\OA;

use App\Http\Controllers\Controller;
use App\Http\Controllers\OATrait\OATrait;
use App\Http\Requests\CommonFormRequest;
use App\Http\Resources\CommonFormResource;
use App\Model\CommonForm;
use Illuminate\Http\Request;

class CommonFormController extends Controller
{
    use OATrait;
    public function index(Request $request)
    {
        $list = CommonForm::query()
                ->when($request->filled('type'),function ($q) use ($request){
                    return $q->where('type',$request->type);
                })
               ->when($request->filled('title'),function ($q) use ($request){
                   return $q->where('title','like',trim($request->title) . '%');
               })
            ->paginate($request->pageSize ?? 10);
        return $this->SucRes(CommonFormResource::collection($list));
    }


    //创建
    public function store(CommonFormRequest $request)
    {
        $form = CommonForm::query()->create($request->validated());
        if($request->filled('files') && !empty($request->files)){
            $this->saveFileList($form->id,$request->input('files',[]),FILE_COMMON_FORM);
        }
        return $this->SucRes(['form_id'=>$form->id]);
    }

    //更新
    public function update(CommonFormRequest $request,CommonForm $form)
    {
        $form->fill($request->validated())->save();
        if($request->filled('files') && !empty($request->files)){
            //$form->files()->delete();
            $this->saveFileList($form->id,$request->input('files',[]),FILE_COMMON_FORM);
        }
        return $this->SucRes();
    }

    public function destroy(CommonForm $form)
    {
        $form->files()->delete();
        $form->delete();
        return $this->SucRes();
    }

    public function show(CommonForm $form)
    {
        return $this->SucRes(CommonFormResource::make($form));
    }
}
